import { login, logout, getInfo } from '@/api/user/index.js'
import { getToken, setToken, removeToken, setStateSync, getStateSync, removeState} from '@/utils/auth.js'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
	id: -1,
	number:'',
	phone:'',
	job:''
	
  }
}

const state = getStateSync() ? JSON.parse(getStateSync())  :getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_NUMBER: (state, number) => {
    state.number = number
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_JOB: (state, job) => {
    state.job = job
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { number, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ number: number.trim(), password: password }).then(response => {
		console.log(response.result)
        commit('SET_TOKEN', response.result.token) 
		commit('SET_ID', response.result.userinfo.id)
        setToken(response.result.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit },id) {
	  console.log("状态管理中的id"+id)
    return new Promise((resolve, reject) => {
      getInfo(id).then(response => {
		console.log(response)
        if (!response) {
          reject('Verification failed, please Login again.')
        }
		
		console.log(response)
        commit('SET_NAME', response.result.name)
        commit('SET_NUMBER', response.result.number)
        commit('SET_PHONE', response.result.phone)
        commit('SET_JOB', response.result.job)
		//将状态本地化
		setStateSync(state)
		console.log(JSON.parse(getStateSync()))
		console.log("-------------------------")
		console.log(state)
		
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
        removeToken() // must remove  token  first
		removeState()
        commit('RESET_STATE')
        resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  // 设置头像
  setAvatar({ commit }, avatar) {
    return new Promise(resolve => {
      commit('SET_AVATAR', avatar)
      resolve()
    })
  }


}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

